import { queryOptions } from "@tanstack/react-query";
import type { InferResponseType } from "hono/client";
import { client } from "@/lib/rpc";

const $reportNames = client.reports.names.$get;
export type ReportNames = InferResponseType<typeof $reportNames>["data"];

export const reportNamesQueryOptions = queryOptions({
  queryKey: ["reportNames"],
  queryFn: async () => {
    const res = await client.reports.names.$get();
    if (!res.ok) throw new Error("Failed to fetch report names");
    const data = await res.json();
    if (!data.ok) throw new Error("Failed to fetch report names");
    return data.data;
  },
});

export const reportsQueryOptions = queryOptions({
  queryKey: ["reports"],
  queryFn: async () => {
    const res = await client.reports.$get({ query: {} });
    if (!res.ok) throw new Error("Failed to fetch reports");
    const data = await res.json();
    if (!data.ok) throw new Error("Failed to fetch reports");
    return data.data;
  },
});

export function reportQueryOptions(id: string) {
  return queryOptions({
    queryKey: ["report", id],
    queryFn: async () => {
      const res = await client.reports[":id"].$get({
        param: { id },
      });
      if (!res.ok) throw new Error("Failed to fetch report");
      const data = await res.json();
      if (!data.ok || data.data === null) throw new Error("Failed to fetch report");
      return data.data;
    },
    enabled: !!id,
  });
}

export const reportsSyncQueryOptions = queryOptions({
  queryKey: ["reports_sync"],
  queryFn: async () => {
    const data = await client.reports.sync.$get();
    return await data.json();
  },
});
